package com.tang.web_standard.global.exception;

import com.tang.web_standard.global.response.Result;
import com.tang.web_standard.global.response.ResultBuilder;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;

/**
 * @Author tangyuan2meicloud.com
 * @DATE 2021/9/16 19:41
 * @Desc
 * @Remarks
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public Result handler(Exception e) {
        return ResultBuilder.error(e.getMessage());
    }

    /**
     * 校验异常全局捕获
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        return ResultBuilder.error(e.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * ValidationException
     */
    @ExceptionHandler(ValidationException.class)
    public Result handleValidationException(ValidationException e) {
        return ResultBuilder.error(e.getCause().getMessage());
    }

    /**
     * ConstraintViolationException
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result handleConstraintViolationException(ConstraintViolationException e) {
        return ResultBuilder.error(e.getMessage());
    }

}
